#pragma once

#include <iostream>
#include <string>
#include <functional>
#include <cerrno>
#include <cstring>
#include <pthread.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include "err.hpp"
#include"ThreadPool.hpp"
#include"Task.hpp"

namespace nt_server
{
    const uint16_t default_port=8888;//默认端口号
    const int backlog=32;          //全连接队列的最大长度

    using func_t = std::function<std::string(std::string)>;//回调函数(参数和返回值均为string)

    class TcpServer;//前置声明

    class ThreadDate
    {
    public:
        ThreadDate(int sock,const std::string& ip,const uint16_t& port,TcpServer* ptr)
        :_sock(sock),_clientip(ip),_clientport(port),_current(ptr)
        {}

    public:
        int _sock;
        std::string _clientip;
        uint16_t _clientport;
        TcpServer *_current;
    };

    class TcpServer
    {
         using func_t = std::function<std::string(std::string)>; 
    public:

        TcpServer(const func_t &func, const uint16_t port = default_port)
            : _func(func),_port(port), _quit(false)
        {
        }

        ~TcpServer(){}

        void InitServer()
        {
            //1.创建监听套接字
            _listensock=socket(AF_INET,SOCK_STREAM,0);
            if(_listensock==-1)
            {
                perror("Create listensock Fail ");
                exit(SOCKET_ERR);
            }

            std::cout<<"Create Socket succss"<<std::endl;

            //2.绑定IP地址和端口号
            struct sockaddr_in local;
            memset(&local,0,sizeof(local));
            local.sin_family=AF_INET;
            local.sin_port=htons(_port);
            local.sin_addr.s_addr=INADDR_ANY;

            
            if(bind(_listensock,(const sockaddr*)&local,sizeof(local))==-1)
            {
                perror("Bind Fail");
                exit(BIND_ERR);
            }

            //3..监听
            if(listen(_listensock,backlog)==-1)
            {
                perror("Listen Fail");
                exit(LISTEN_ERR);
            }

            std::cout<<"Listen success "<<std::endl;
        }

        void StartServer()
        {
            //读到数据，让线程处理业务
            while(!_quit)
            {
                //1.处理连接请求
                struct sockaddr_in client;
                socklen_t len=sizeof(client);

                int sock=accept(_listensock,(struct sockaddr*)&client,&len);
                
                //请求失败也继续请求
                if(sock==-1)
                {
                    perror("Accept Fail");
                    continue;
                }

                //连接成功，获取客户端信息
                std::string clientip=inet_ntoa(client.sin_addr);
                uint16_t clientport=ntohs(client.sin_port);

                std::cout<<"Server accept "<<clientip<<"-"<<clientport<<" "<<sock<<"from"<<_listensock<<" success"<<std::endl;

                Yohifo::Task t(sock, clientip, clientport, std::bind(&TcpServer::Service, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3));

                Yohifo::ThreadPool<Yohifo::Task>::getInstance()->pushTask(t);
            }
        }

        static void* Routine(void* args)
        {
            //线程分离
            pthread_detach(pthread_self());

            ThreadDate* td=static_cast<ThreadDate*>(args);

            td->_current->Server(td->_sock,td->_clientip,td->_clientport);

            delete td;
        }

        //服务器业务处理
        void Server(int sock,const std::string& clientip,const uint16_t& clientport)
        {
            char buff[1024];
            std::string who=clientip+"-"+std::to_string(clientport);
            while(true)
            {
                ssize_t n=read(sock,buff,sizeof(buff)-1);

                //判断是否读到数据
                if(n>0)
                {
                    buff[n]='\0';
                    std::cout<<"Server get: "<<buff<<" from "<<who<<std::endl;

                    //处理发来的信息
                    std::string respond=_func(buff);

                    //发送给服务器
                    write(sock,buff,strlen(buff));
                }
                else if(n==0)
                {
                    //读到文件结尾，读取结束
                    std::cout<<"Client "<<who<<" "<<sock<<" quit"<<std::endl;
                    close(sock);//关闭文件描述符
                    break;
                }
                else
                {
                    perror("Read Fail");
                    break;
                }
            }
        }
    private:
        int _listensock;
        uint16_t _port;
        bool _quit;
        func_t _func;
    };
}